<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// tag helpers -----------------------------------------------------------------

/**
 * Generate a script tag to include javascript file
 *
 * @access	public
 * @return	the script tag
 */
if ( ! function_exists('js_src'))
{
	function js_src($path)
	{
		$real = substr($path, 0, 5) == 'http:' ? $path : base_url().'javascript/'.$path;
		return '<script src="'.$real.'" type="text/javascript"></script>';
	}
}

/**
 * Generate an img tag to display an icon from /images/icons/
 * @return img tag
 */

function icon_tag($name, $extra = '')
{
	return '<img src="'.base_url().'images/icons/'.$name.'.png" alt="'.$name.'" class="icon" '.$extra.'/>';
}

/**
 * Generate a tooltip message, displayed when the help icon is hovered
 * @return span tag
 */
function tooltip_tag($message)
{
	return '<span class="tooltip">'.icon_tag('help').'<span>'.$message.'</span></span>';
}

/**
 * HTML5 input number (requires form helper)
 * @return input number tag
 */
function form_number($data = '', $value = '', $extra = '')
{
	$defaults = array('type' => 'number', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value);
	return "<input "._parse_form_attributes($data, $defaults).$extra." />";
}

function js_anchor($js_target, $name, $extra = '')
{
	return '<a href="javascript:'.$js_target.'" '.$extra.'>'.$name.'</a>';
}


// buttons helper --------------------------------------------------------------

function button_submit($name = 'Valider', $icon = 'tick', $extra = '')
{
	// we use button tag instead of input to allow inner HTML (images, improved styling...)
	return '<button type="submit" class="js-button" '.$extra.'>'.$name.' '.icon_tag($icon).'</button>';
}

function button_cancel($target)
{
	return button_link($target, 'Annuler', 'cancel');
}

function button_add($target)
{
	return button_link($target, 'Nouveau', 'add');
}

function button_link($target, $name, $icon)
{
	return anchor($target, $name.' '.icon_tag($icon), 'class="js-button"');
}


/**
 * Generate a stylised link button
 * @return anchor tag
 */
function nice_button($url, $name, $options = array())
{
	$options['class'] = isset($options['class']) ? $options['class'].' apple-button' : 'apple-button';
	return anchor($url, '<span>'.$name.'</span>', $options);
}


// datetime --------------------------------------------------------------------


/**
 * Date au format SQL Datetime depuis un timestamp unix
 * @param unix_time: timestamp unix (NULL pour date courante)
 */
function date_db_format($unix_time = NULL)
{
	date_default_timezone_set('Europe/Paris');
	return strftime('%Y-%m-%d %H:%M:%S', $unix_time == NULL ? time() : $unix_time);
}

/**
 * Generate well-formated dates from datetime value (string)
 * @return	the string containing the formatted date
 */
function time_to_str($str_datetime)
{
	$d = new DateTime($str_datetime);
	return $str_datetime ? $d->format('d/m/Y') : '-';
}

function time_to_str_short($str_datetime)
{
	$d = new DateTime($str_datetime);
	return $str_datetime ? $d->format('d/m/y') : '-';
}

function time_to_str_long($str_datetime)
{
	$d = new DateTime($str_datetime);
	return $str_datetime ? $d->format('d/m/Y à H:i') : '-';
}

function timestamp_to_str($timestamp)
{
	return date('d/m/Y', $timestamp);
}

function date_news_to_str($str_datetime)
{
	$d = new DateTime($str_datetime);
	return $d->format('d/m/y');
}

// strings ---------------------------------------------------------------------

/**
 * Nettoyer une chaîne de caractères issue d'un formulaire
 */
function clean_str($str)
{
	$str = htmlspecialchars(trim($str));
	if (get_magic_quotes_gpc()) {
		$str = stripslashes($str);
	}
	return $str;
}

/**
 * Variante qui laisse les tags HTML intactes
 */
function clean_str_preserve_tags($str)
{
	$str = trim($str);
	if (get_magic_quotes_gpc()) {
		$str = stripslashes($str);
	}
	return $str;
}

/**
 * @return true si $haystack commence par $needle
 */
function str_startswith($haystack, $needle)
{
	return substr($haystack, 0, strlen($needle)) === $needle;
}

/**
 * @return true si $haystack finit par $needle
 */
function str_endswith($haystack, $needle)
{
  return substr($haystack, -strlen($needle)) === $needle;
}

function parse_template(&$text, $values)
{
	foreach ($values as $key => $value) {
		$text = str_replace('#{'.$key.'}', $value, $text);
	}
}

// misc ------------------------------------------------------------------------

/**
 * Détermine si une adresse e-mail est valide
 * @return true si l'adresse est bonne, sinon false
 */
function check_email($email)
{
	return preg_match('/^([\w._-]+@[0-9a-z._-]+?\.[a-z]{2,4})$/i', $email);
}

/**
 * Détermine si une date de naissance est valide
 */
function check_bithdate($date)
{
	return preg_match('/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/i', $date);
}

/*
 * Retourne une chaîne représentant des octets dans l'unité adéquate
 */
function bytes_symbol($bytes)
{
    $symbols = array('octets', 'Kio', 'Mio', 'Gio', 'Tio', 'Pio', 'Eio', 'Zio', 'Yio');
    $exp = $bytes ? floor(log($bytes) / log(1024)) : 0;

    return sprintf('%.2f '.$symbols[$exp], $bytes / pow(1024, floor($exp)));
}

function ext_to_icon($ext)
{
	switch (strtolower($ext))
	{
		case 'pdf':
			return 'page_white_acrobat';
		case 'rb':
			return 'page_white_ruby';
		case 'php':
			return 'page_white_php';
		case 'sql':
			return 'page_white_database';
		case 'swf':
			return 'page_white_flash';
		case 'odt': case 'doc': case 'docx':
			return 'page_white_word';
		case 'ods': case 'xls': case 'xlsx':
			return 'page_white_excel';
		case 'ppt': case 'pptx':
			return 'page_white_powerpoint';
		case 'jpg': case 'jpeg': case 'png': case 'gif':
			return 'picture';
		case 'zip': case 'rar': case 'gz': case '7z':
			return 'compress';
		default:
			return 'page_white_text';
	}
}

/**
 * Generate a special hash from a sha1 hashed string
 *
 * @access	public
 * @return	the 'special' hash
 */
if ( ! function_exists('crypt_password'))
{
	function crypt_password($password)
	{
		$hash = sha1($password);
		$inverted = '';
		$j = 0;
		for($i=0 ; $i < strlen($hash) ; ++$i)
		{
			$inverted .= substr($hash,$j+1,1);
			$inverted .= substr($hash,$j,1);
			$j += 2;
		}
		return $inverted;
	}
}

/**
 * Génération d'un password aléatoire
 * @param size: la taille désirée pour le password (6 par défaut)
 * @return une chaîne de caractères composées de chiffres et lettres minuscules de N caractères (N = size)
 */
if ( ! function_exists('generate_password'))
{
	function generate_password($size = 6)
	{
		return strtolower(substr(base64_encode(md5(rand())), 0, $size));
	}
}

/**
 * Obtenir un code de sécurité aléatoire à 4 chiffres
 */
if ( ! function_exists('security_code'))
{
	function security_code()
	{
		return substr(md5(rand()), 3, 4);
	}
}

/**
 * Permet de savoir si $word est une version incrémentée de $base (pour 'truc': ça match 'truc0', 'truc3', 'truc25'...)
 */
if ( ! function_exists('is_incremented_word'))
{
	function is_incremented_word($base, $word)
	{
		return preg_match('/^('.$base.')([0-9]+)?$/i', $word);
	}
}

/**
 * Afficher un tableau sous form de liste
 */
if ( ! function_exists('print_array'))
{
	function print_array($tab)
	{
		$list = '<ul class="list">';
		foreach ($tab as $item)
			$list .= '<li>'.$item.'</li>';
		$list .= '</ul>';
		return $list;
	}
}
